package server

import (
	"common/config"
	"context"
	"errors"
	"sync"
	"ticket_srv/internal/model/dao"
	pb "ticket_srv/proto"
)

type Server struct {
	pb.UnimplementedTicketServer
}

func (Server) FindDate(ctx context.Context, request *pb.FindDateRequest) (*pb.FindDateResponse, error) {
	var ticket []dao.Ticket
	config.DB.Where("date=?", request.Date).Find(&ticket)
	var sli []*pb.Tickets
	for _, d := range ticket {
		one := pb.Tickets{
			MoverTheater: d.MoverTheater,
			MovieName:    d.MovieName,
			MoveType:     int64(d.MoveType),
			MoveLanguage: int64(d.MoveLanguage),
			Date:         d.Date,
			BeginTime:    d.BeginTime.String(),
			EndTime:      d.EndTime.String(),
			MovieHouse:   int64(d.MovieHouse),
			SetNum:       int64(d.SetNum),
			TicketPrice:  float32(d.TicketPrice),
		}
		sli = append(sli, &one)
	}
	return &pb.FindDateResponse{Ticket: sli}, nil
}

func (Server) FindTicket(ctx context.Context, request *pb.FindTicketRequest) (*pb.FindTicketResponse, error) {
	var ticket []dao.TicketSeat
	config.DB.Where("user_id=?", request.UserId).Find(&ticket)
	var tickets []dao.Ticket
	for _, s := range ticket {
		var one dao.Ticket
		config.DB.Where("id=?", s.TicketId).Find(&one)
		tickets = append(tickets, one)
	}
	var sli []*pb.Tickets
	for _, d := range tickets {
		one := pb.Tickets{
			MoverTheater: d.MoverTheater,
			MovieName:    d.MovieName,
			MoveType:     int64(d.MoveType),
			MoveLanguage: int64(d.MoveLanguage),
			Date:         d.Date,
			BeginTime:    d.BeginTime.String(),
			EndTime:      d.EndTime.String(),
			MovieHouse:   int64(d.MovieHouse),
			SetNum:       int64(d.SetNum),
			TicketPrice:  float32(d.TicketPrice),
		}
		sli = append(sli, &one)
	}
	return &pb.FindTicketResponse{Ticket: sli}, nil
}

func (Server) CreateTicket(ctx context.Context, request *pb.CreateTicketRequest) (*pb.CreateTicketResponse, error) {
	var seat *dao.TicketSeat
	mutex := sync.Mutex{}
	mutex.Lock()
	config.DB.Where("seat=? and ticket_id=?", request.Seat, request.TicketId).Find(&seat)
	if seat.ID != 0 {
		return nil, errors.New("购票失败,这个座位有人了")
	}
	ticket := dao.TicketSeat{
		TicketId: int(request.TicketId),
		Seat:     int(request.Seat),
		UserId:   int(request.UserId),
	}
	err := config.DB.Create(&ticket).Error
	if err != nil {
		return nil, errors.New("购票失败")
	}
	mutex.Unlock()
	return &pb.CreateTicketResponse{Id: int64(ticket.ID)}, nil
}

func (Server) FindSeat(ctx context.Context, request *pb.FindSeatRequest) (*pb.FindSeatResponse, error) {
	var ticket []dao.TicketSeat
	config.DB.Where("ticket_id=?", request.TicketId).Find(&ticket)
	var haveTicket []int
	for _, s := range ticket {
		haveTicket = append(haveTicket, s.Seat)
	}
	var tickets dao.Ticket
	config.DB.Where("id=?", request.TicketId).Find(&tickets)
	var sli []int64
	for i := 1; i <= tickets.SetNum; i++ {
		for _, d := range haveTicket {
			if i != d {
				sli = append(sli, int64(i))
			}
		}
	}
	return &pb.FindSeatResponse{Seat: sli}, nil
}
